package com.hxzon.aixzsecretary.net;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.Date;

import javax.swing.JOptionPane;

public class FileClient extends Thread {
	private String IP;
	private int port = 3002;
	private String myname;
	private String myIP;
	private String filepath;

	public FileClient(String IP, String myname, String myIP, String filepath) {
		this.IP = IP;
		this.myname = myname;
		this.myIP = myIP;
		this.filepath = filepath;
	}

	public void run() {
		try {
			File file = new File(filepath);
			float filelength1 = (int) file.length();
			String filelength = "";
			DecimalFormat df = new DecimalFormat("0.00");
			if (filelength1 > 1024 * 1024 * 1024)
				filelength = String.valueOf(df.format(filelength1
						/ (1024 * 1024 * 1024)))
						+ "GB";
			else if (filelength1 > 1024 * 1024)
				filelength = String.valueOf(df.format(filelength1
						/ (1024 * 1024)))
						+ "MB";
			else if (filelength1 > 1024)
				filelength = String.valueOf(df.format(filelength1 / (1024)))
						+ "KB";
			else if (filelength1 > 0)
				filelength = String.valueOf(df.format(filelength1)) + "B";

			Socket socket = new Socket(IP, port);
			DataInputStream dis = new DataInputStream(// 改成ObjectInputStream会出错
					new BufferedInputStream(socket.getInputStream()));
			ObjectOutputStream dos = new ObjectOutputStream(
					new BufferedOutputStream(socket.getOutputStream()));
			DataInputStream fis = new DataInputStream(new BufferedInputStream(
					new FileInputStream(filepath)));
			int bufferSize = 81920;
			byte[] buf = new byte[bufferSize];
			dos.writeUTF(myname);
			dos.flush();
			dos.writeUTF(myIP);
			dos.flush();
			dos.writeObject(new Date());
			dos.flush();

			dos.writeFloat(filelength1);
			dos.flush();
			dos.writeUTF(file.getName());
			dos.flush();
			dos.writeUTF(filelength);
			dos.flush();

			String reply = dis.readUTF();
			if (reply.equals("yes")) {
				while (true) {
					int read = 0;
					if (fis != null)
						read = fis.read(buf);
					if (read == -1)
						break;
					dos.write(buf, 0, read);
					dos.flush();
				}// end while
				// JOptionPane.showMessageDialog(null,"对方已接收文件", "received", 1);
			} else
				JOptionPane.showMessageDialog(null, "对方拒绝接收文件", "rejected", 1);

			dis.close();
			dos.close();
			fis.close();
		} catch (Exception e) {
		}
	}// end run

}
